package com.atguigu.gulimall.member.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    //@Autowired
    //MemberLevelDao memberLevelDao;
    @Override
    public void regist(MemberRegistVo vo) {

        MemberEntity entity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;
        //设置默认等级
        //MemberLevelEntity levelEntity= memberLevelDao.getDefaultLevel();

        entity.setLevelId(1L);

        //检查用户名和手机号是否唯一，因为用户要通过用户名和手机号登陆
        //使用异常机制感知异常
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());

        //不能给数据库保存明文密码,要加密保存，使用MD5加密算法
        //彩虹表中都保存了，暴力破解了

        //盐值加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        memberDao.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{

        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer username = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if(username>0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //1、数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if(member==null){
            //登陆失败
            return null;
        }else {
            //数据库的passwod
            String passwordDb = member.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, passwordDb);
            if (matches) {
                return member;
            } else {
                return null;
            }
        }
    }

    //社交登陆重载方法
    @Override
    public MemberEntity login(SocialUser socialUser){

        //登陆和注册合并
        String id = socialUser.getId();
        //1、判断是否登陆过
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", id));

        if(memberEntity != null){
            //这个用户已经存在,更新access_token,过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            memberDao.updateById(update);

            //返回 memberEntity
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());

            return memberEntity;

        }else{

            //没有查到记录，需要注册一个
            MemberEntity regist = new MemberEntity();
            try{
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token",socialUser.getAccess_token());
                HttpResponse response = HttpUtils.doGet("http://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);
                if(response.getStatusLine().getStatusCode()==200){
                    //查询成功socialUser是包含id的token类
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    regist.setNickname(name);
                    regist.setLevelId(1L);
                }
            }catch (Exception e){}  //非关键信息即使出现问题，也不管

            //将关键信息插入就好了
            regist.setSocialId(socialUser.getId());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            //查询社交信息，昵称等等

            //插入注册
            memberDao.insert(regist);

            //返回实体类
            return regist;
        }
    }
}